package com.nts.pmchelperdemo3.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nts.pmchelperdemo3.constant.MessageConstant;
import com.nts.pmchelperdemo3.dto.ToolDTO;
import com.nts.pmchelperdemo3.entity.Order;
import com.nts.pmchelperdemo3.entity.Tool;
import com.nts.pmchelperdemo3.exception.BeRelatedException;
import com.nts.pmchelperdemo3.exception.ToolExistException;
import com.nts.pmchelperdemo3.exception.ToolNullException;
import com.nts.pmchelperdemo3.mapper.OrderMapper;
import com.nts.pmchelperdemo3.mapper.ToolMapper;
import com.nts.pmchelperdemo3.service.ToolService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ToolServiceImpl implements ToolService {
    @Autowired
    private ToolMapper toolMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Override
    @Transactional
    public ToolDTO createTool(ToolDTO toolDTO)
    {
        QueryWrapper<Tool> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tool_name",toolDTO.getToolName());
        if (toolMapper.selectCount(queryWrapper) > 0)
        {
            throw new ToolExistException(MessageConstant.TOOL_ALREADY_EXISTS);
            //ResultUtil.throwException("刀具名称已存在");
        }
        //保存刀具（仅普通刀）

        Tool tool = new Tool();
        BeanUtils.copyProperties(toolDTO,tool);
        tool.setType(0);//普通刀
        toolMapper.insert(tool);

        toolDTO.setId(tool.getId());
        return toolDTO;
    }

    @Override
    public List<ToolDTO> queryTools(String toolName,Integer page,Integer size)
    {
        Page<Tool>pageQuery = new Page<>(page,size);
        QueryWrapper<Tool>queryWrapper = new QueryWrapper<>();
        if (toolName != null && !toolName.isEmpty()){
            queryWrapper.like("tool_name",toolName);
        }
        IPage<Tool>toolPage = toolMapper.selectPage(pageQuery,queryWrapper);
        return toolPage.getRecords().stream().map(this::convertToDTO).collect(Collectors.toList());
    }

    @Override
    public ToolDTO getToolById(Long id)
    {
        Tool tool = toolMapper.selectById(id);
        if (tool == null)
        {
            throw new ToolNullException(MessageConstant.TOOL_IS_NULL);
            //ResultUtil.throwException("刀具不存在");
        }
        return convertToDTO(tool);
    }

    @Override
    public Tool getToolByName(String toolName)
    {
        QueryWrapper<Tool>queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tool_name",toolName);
        return toolMapper.selectOne(queryWrapper);
    }

    @Override
    @Transactional
    public ToolDTO updateTool(Long id,ToolDTO toolDTO)
    {
        Tool tool =toolMapper.selectById(id);
        if (tool == null)
        {
            throw new ToolNullException(MessageConstant.TOOL_IS_NULL);
            //ResultUtil.throwException("刀具不存在");
        }
        //修改名称验证
        if (!tool.getToolName().equals(toolDTO.getToolName()))
        {
            QueryWrapper<Tool>queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("tool_name",toolDTO.getToolName());
            if (toolMapper.selectCount(queryWrapper) > 0)
            {
                throw new ToolExistException(MessageConstant.TOOL_ALREADY_EXISTS);
                //ResultUtil.throwException("新刀具名称已存在");
            }
        }

        BeanUtils.copyProperties(toolDTO,tool);
        toolMapper.updateById(tool);
        return convertToDTO(tool);
    }

    @Override
    @Transactional
    public void deleteTool(Long id)
    {
        Tool tool = toolMapper.selectById(id);
        if (tool == null)
        {
            throw new ToolNullException(MessageConstant.TOOL_IS_NULL);
            //ResultUtil.throwException("刀具不存在");
        }

        //检查关联订单
        QueryWrapper<Order>orderQuery = new QueryWrapper<>();
        orderQuery.eq("tool_name",tool.getToolName());
        if (orderMapper.selectCount(orderQuery) > 0)
        {
            throw new BeRelatedException(MessageConstant.TOOL_BE_RELATED_BY_ORDER);
            //ResultUtil.throwException("刀具存在关联订单，无法删除");
        }
        toolMapper.deleteById(id);
    }

    @Override
    public int countAllTools(){
        return toolMapper.selectCount(null);
    }

    //转DTO
    private ToolDTO convertToDTO(Tool tool)
    {
        ToolDTO dto = new ToolDTO();
        BeanUtils.copyProperties(tool,dto);
        dto.setTypeName(tool.getType() == 0 ? "普通刀" : "定制刀");
        return dto;
    }


}
